﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Configuration;

namespace LenderClearingHouse
{
    public partial class PropertyDetails2 : PageBase
    {
        private static string[] ImageExt = { ".bmp", ".jpeg", ".jpg", ".gif", ".png" };
        protected string EditPropertyUrl
        {
            get
            {
                string result = ResolveClientUrl("~/");
                switch (SourcePage)
                {
                    case LenderClearingHouse.SourcePage.RentProjection:
                        result += "RentProjection.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.MasterList:
                        result += "MasterList.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.WorkingList:
                        result += "WorkingList.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.LvreoList:
                        result += "LvreoMasterListEx.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.EscrowList:
                        result += "EscrowList.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.RehabList:
                        result += "RehabList.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.LvreoMasterEdit:
                        result += "LvreoMasterList.aspx";
                        break;
                    case LenderClearingHouse.SourcePage.GlobalGrid:
                        result += "GlobalGrid.aspx";
                        lnkEdit.Visible = false;
                        break;

                }

                string location = "";
                string details = "";
                string apn = "";
                GetPropertyInfo(out location, out details, out apn);
                result += "?apn=" + Server.UrlEncode(apn) + "&edit=1";

                return result;
            }
        }


        protected bool ShowGallery
        {
            get
            {
                if (ViewState["ShowGallery"] == null)
                    return false;

                return Convert.ToBoolean(ViewState["ShowGallery"]);
            }
            set
            {
                ViewState["ShowGallery"] = value;
            }
        }

        protected SourcePage SourcePage
        {
            get { return (SourcePage)Session["SourcePage"]; }
        }

        bool Editable
        {
            get
            {
                return CurrentUser.UserRole == UserRole.SuperAdmin
                || CurrentUser.UserRole == UserRole.EscrowUser 
                || (SourcePage == SourcePage.LvreoList && CurrentUser.LvreoRole == RoleAccess.ReadWrite)
                || (SourcePage == SourcePage.LvreoMasterEdit && CurrentUser.LvreoRole == RoleAccess.ReadWrite)
                || (SourcePage == SourcePage.SdreoList && CurrentUser.SdreoRole == RoleAccess.ReadWrite)
                || (SourcePage == SourcePage.MasterList && CurrentUser.MasterlistRole == RoleAccess.ReadWrite);
            }
        }

        bool HasUserAccessToFolder(string folderName)
        {
            if (CurrentUser.UserRole == UserRole.ProjectManager) return false;
            if (CurrentUser.UserRole == UserRole.SuperAdmin) return true;
            //if ((CurrentUser.UserRole == UserRole.InvestorAdmin) || (CurrentUser.UserRole == UserRole.InvestorUser)) return true;

            if (SourcePage == SourcePage.MasterList)
                if (CurrentUser.MasterlistRole != RoleAccess.NoAccess) return true;

            DataRow dr = DocumentFolders.Select("FolderName='" + folderName + "'")[0];
            switch (CurrentUser.UserRole)
            {
                case UserRole.EscrowUser: return dr["EscrowUserRole"].ToString() != "NA";
                case UserRole.InvestorUser: return dr["InvestorRole"].ToString() != "NA";
                case UserRole.InvestorAdmin: return dr["InvestorAdminRole"].ToString() != "NA";
                case UserRole.User: return dr["UserRole"].ToString() != "NA";
                default: return false;
            }
        }

        bool CanUserEditFolder()
        {
            if (CurrentUser.UserRole == UserRole.ProjectManager) return false;
            if (CurrentUser.UserRole == UserRole.SuperAdmin) return true;

            if (string.IsNullOrEmpty(CurrentFoldersPath))
            {
                return false;
            }

            if (SourcePage == SourcePage.MasterList)
                return CurrentUser.MasterlistRole == RoleAccess.ReadWrite;

            DataRow dr = DocumentFolders.Select("FolderName='" + CurrentFoldersPath.Split('\\')[0] + "'")[0];
            switch (CurrentUser.UserRole)
            {
                case UserRole.EscrowUser: return dr["EscrowUserRole"].ToString() == "RW";
                case UserRole.InvestorUser: return dr["InvestorRole"].ToString() == "RW";
                case UserRole.InvestorAdmin: return dr["InvestorAdminRole"].ToString() == "RW";
                case UserRole.User: return dr["UserRole"].ToString() == "RW";
                default: return false;
            }
        }

        public const string STR_WE_ARE_ON_DETAILS = "STR_WE_ARE_ON_DETAILS";

        protected void Page_Load(object sender, EventArgs e)
        {
            Session[STR_WE_ARE_ON_DETAILS] = "1";

            string location = "";
            string details = "";
            string apn = "";
            GetPropertyInfo(out location, out details, out apn);
	        lnkAddress.Text = location;
			lnkAddress.NavigateUrl = string.Format("http://maps.google.com/?q={0}", location);
            lbDetails.Text = details;

            EnsurePropertyDirs(location, apn);
            lnkEdit.NavigateUrl = EditPropertyUrl;

            RefreshImagesGallery();
            RefreshGalleryVisible();

            if (IsPostBack)
            {
                return;
            }
            
            RefreshImages();
            if (SortedPropertyIds != null)
            {
                int idx = -1;
                for (int i = 0; i < SortedPropertyIds.Length; i++)
                {
                    if (SortedPropertyIds[i].ToString() == PropertyId)
                    {
                        idx = i;
                        break;
                    }
                }

                if (idx < 0)
                {
                    btnPrevProperty.Visible = false;
                    btnNextProperty.Visible = false;
                }
                else
                {
                    btnPrevProperty.Visible = true;
                    btnNextProperty.Visible = true;

                    if (idx > 0)
                    {
                        btnPrevProperty.PostBackUrl = "~/PropertyDetails2.aspx?PropertyId=" + SortedPropertyIds[idx - 1];
                    }
                    else
                    {
                        btnPrevProperty.Visible = false;
                    }

                    if (idx < SortedPropertyIds.Length - 1)
                    {
                        btnNextProperty.PostBackUrl = "~/PropertyDetails2.aspx?PropertyId=" + SortedPropertyIds[idx + 1];
                    }
                    else
                    {
                        btnNextProperty.Visible = false;
                    }
                }
            }
                        
                        
            DoNormalization(PropertyPhysicalDir);

            hlPropertyDetails.NavigateUrl = Request.Url.ToString();
            panelUpload.Visible = Editable;

            GoToFolder("");
        }

        string PropertyVirtualDir
        {
            get { return Session["PropertyVirtualDir"].ToString(); }
            set { Session["PropertyVirtualDir"] = value.Replace("#", "%23"); }
        }

        string PropertyPhysicalDir
        {
            get { return Session["PropertyPhysicalDir"].ToString(); }
            set { Session["PropertyPhysicalDir"] = value; }
        }

        string PropertyGalleryPhysicalDir
        {
            get { return Path.Combine(PropertyPhysicalDir, "Gallery"); }
        }

        string CurrentFoldersPath
        {
            get
            {
                var result = Session["CurrentFoldersPath"] as string;
                if (result == null)
                {
                    result = "";
                    Session["CurrentFoldersPath"] = result;
                }
                return result;
            }
            set
            {
                Session["CurrentFoldersPath"] = value;
            }
        }

        string CurrentFoldersPathForImages
        {
            get
            {
                if (string.IsNullOrEmpty(CurrentFoldersPath))
                    return "Gallery";
                else
                    return CurrentFoldersPath;
            }
        }

        /// <summary>
        /// создает на диске все дерево директорий для данной проперти
        /// </summary>
        /// <param name="location"></param>
        private void EnsurePropertyDirs(string location, string apn)
        {
            string rootDir = Server.MapPath("~/PropertiesFiles");
            if (SourcePage == LenderClearingHouse.SourcePage.SdreoList)
            {
                rootDir = Path.Combine(rootDir, "SDREO");
                PropertyVirtualDir = "~/PropertiesFiles/SDREO/" + location;
            }
            else
            {
                rootDir = Path.Combine(rootDir, "LVREO");
                PropertyVirtualDir = "~/PropertiesFiles/LVREO/" + location;
            }

            PropertyPhysicalDir = Path.Combine(rootDir, location);
            if (!Directory.Exists(PropertyPhysicalDir))
            {
                Directory.CreateDirectory(PropertyPhysicalDir);
                PropertiesFilesLog(Session["User"] as User, PropertyPhysicalDir, apn);
            }

            DataAccess da = new DataAccess();
            DocumentFolders = da.ExecuteSQL("select * from DocumentFolder");
            foreach (DataRow dr in DocumentFolders.Rows)
            {
                string folderDir = Path.Combine(PropertyPhysicalDir, dr["FolderName"].ToString());
                if (!Directory.Exists(folderDir))
                {
                    Directory.CreateDirectory(folderDir);
                    PropertiesFilesLog(Session["User"] as User, folderDir, apn);
                }
            }
        }

        public static void PropertiesFilesLog(User usr, string folder, string apn)
        {
            DataAccess da = new DataAccess();
            da.ExecuteSQL(string.Format(
                "insert into PropertiesFilesLog(FolderName, CurrentUser, Apn) values('{0}', '{1}', '{2}')",
                folder.Replace("'", "''"),
                usr != null ? usr.UserName : "",
                apn));
        }

        DataTable DocumentFolders
        {
            get { return (DataTable)Session["DocumentFolders"]; }
            set { Session["DocumentFolders"] = value; }
        }

        string PropertyGalleryVirtualDir
        {
            get
            {
                return PropertyVirtualDir + "/Gallery/";
            }
        }

        int[] SortedPropertyIds
        {
            get { return Session["AllPropertiesIds"] as int[]; }
        }

        void GetPropertyInfo(out string location, out string details, out string apn)
        {
            string spName = null;
            location = "";
            details = "";
            apn = "";

            switch (SourcePage)
            {
                case SourcePage.MasterList:
                    spName = "getPropertyInfo"; break;
                case SourcePage.WorkingList:
                    spName = "getPropertyInfoWorkingList"; break;  
                case SourcePage.Archive:
                    spName = "getPropertyInfo"; break;
                case SourcePage.LvreoList: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.LvreoMasterEdit: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.EscrowList: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.RehabList: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.GlobalGrid: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.RentProjection: spName = "getLvreo_PropertyInfo"; break;
                case SourcePage.SdreoList: spName = "getSdreo_PropertyInfo"; break;
                default: throw new Exception();
            }

            DataAccess da = new DataAccess();
            DataTable dt = da.ExecuteSQL(string.Format("{0} {1}", spName, PropertyId));
            if (dt.Rows.Count == 0) return;

            location = dt.Rows[0]["Location"].ToString();
            if (location.EndsWith(", ")) location = location.Remove(location.Length - 2, 2);
            details = dt.Rows[0]["PropertyDetails"].ToString();
            apn = dt.Rows[0]["Apn"].ToString();
        }

        void RefreshFilesList(string path)
        {
            if (string.IsNullOrEmpty(path) && CurrentUser.UserRole != UserRole.SuperAdmin)
            {
                dlFiles.DataSource = null;
            }
            else
            {
                List<string> files = new List<string>();

                DirectoryInfo di = new DirectoryInfo(Path.Combine(PropertyPhysicalDir, path));
                foreach (FileInfo fi in di.GetFiles())
                {
                    files.Add(fi.Name);
                }

                files.Sort();
                dlFiles.DataSource = files;
            }

            dlFiles.DataBind();
        }

        void RefreshBreadcrumb(string path)
        {
            tdImageAddNewFolder.Visible = CanUserEditFolder();
            tdLinkAddNewFolder.Visible = CanUserEditFolder();

            if (string.IsNullOrEmpty(path))
            {
                dlBreadcrumb.DataSource = null;
            }
            else
            {
                List<string> pathList = path.Split('\\').ToList();

                List<string> breadcrumb = new List<string>();
                while (pathList.Count > 0)
                {
                    breadcrumb.Add(string.Join("\\", pathList.ToArray()));
                    pathList.RemoveAt(pathList.Count - 1);
                }

                breadcrumb.Reverse();
                dlBreadcrumb.DataSource = breadcrumb;
            }
            
            dlBreadcrumb.DataBind();
        }

        void RefreshFoldersList(string path)
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("FolderName");
            tbl.Columns.Add("FolderPath");

            DirectoryInfo di = new DirectoryInfo(Path.Combine(PropertyPhysicalDir, path));
            foreach (DirectoryInfo fi in di.GetDirectories())
            {
                // check access to root folders only
                if (string.IsNullOrEmpty(CurrentFoldersPath) && !HasUserAccessToFolder(fi.Name)) continue;
                
                tbl.Rows.Add(fi.Name, Path.Combine(path, fi.Name));
            }

            dlFolders.DataSource = tbl;
            dlFolders.DataBind();
        }

        private void RefreshImages()
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("ImagePath");

            string path = Path.Combine(PropertyPhysicalDir, CurrentFoldersPathForImages);
            
            DirectoryInfo di = new DirectoryInfo(path);
            foreach (FileInfo fi in di.GetFiles())
            {
                if (!PropertyDetails2.ImageExt.Contains(fi.Extension.ToLower()))
                    continue;
                string imgName = Path.GetFileName(fi.FullName);
                tbl.Rows.Add(imgName);
            }

            dlImages.DataSource = tbl;
            dlImages.DataBind();

            RefreshImagesGallery();
            RefreshGalleryVisible();
        }

        private void RefreshImagesGallery()
        {
            phItems.Controls.Clear();

            string path = Path.Combine(PropertyPhysicalDir, CurrentFoldersPathForImages);

            DirectoryInfo di = new DirectoryInfo(path);
            foreach (FileInfo fi in di.GetFiles())
            {
                if (!PropertyDetails2.ImageExt.Contains(fi.Extension.ToLower()))
                    continue;

                string imgName = Path.GetFileName(fi.FullName);

                HtmlImage img = new HtmlImage();
                img.Src = GetFullImageUrl(imgName);
                phItems.Controls.Add(img);
            }
        }

        string GetFullImageUrl(string imagePath)
        {
            return ResolveClientUrl(PropertyVirtualDir + "/"  + CurrentFoldersPathForImages) + "/" + imagePath;
        }

        string PropertyId
        {
            get { return Request.QueryString["propertyId"]; }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                List<string> duplicates = new List<string>();
                string currentFolderName = Path.Combine(PropertyPhysicalDir, CurrentFoldersPath);

                foreach (UploadedFile uf in upload.UploadedFiles)
                {
                    string uploadedFileName = Path.Combine(Server.MapPath(upload.TargetFolder), uf.GetName());
                    string newName = "";

                    foreach (DataRow dr in DocumentFolders.Rows)
                    {
                        if (uf.GetName().ToUpper().StartsWith(dr["Prefix"].ToString().ToUpper() + " "))
                        {
                            string copyToFolderName = Path.Combine(PropertyPhysicalDir, dr["FolderName"].ToString());

                            // файл соответствует префиксу, однако если текущий фолдер есть сабфолдер того фолдера
                            // чьему префиксу соответствует файл. соответственно копировать в корень его не надо
                            if (!currentFolderName.ToUpper().StartsWith(copyToFolderName.ToUpper()))
                            {
                                newName = Path.Combine(copyToFolderName, uf.GetName());
                            }
                            break;
                        }
                    }

                    if (string.IsNullOrEmpty(newName))
                    {
                        newName = Path.Combine(currentFolderName, uf.GetName());
                    }

                    if (File.Exists(newName))
                    {
                        duplicates.Add(uf.GetName());
                    }
                    else
                    {
                        File.Copy(uploadedFileName, newName, true);
                    }
                }

                string message = string.Format("{0} file(s) uploaded", upload.UploadedFiles.Count - duplicates.Count);
                if (duplicates.Count > 0)
                {
                    message += "\\n\\nThese files already exists:\\n" + string.Join("\\n", duplicates.ToArray());
                }

                ScriptManager.RegisterStartupScript(this, this.GetType(),
                        "key", string.Format("alert('{0}');", message), true);

                RefreshImages();
                GoToFolder(CurrentFoldersPath);
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(),
                        "key", string.Format("alert('Error uploading files');"), true);
            }
        }

        public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            // Save resized picture
            NewImage.Save(NewFile);
        }

        protected void dlImages_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView rowView = e.Item.DataItem as DataRowView;

                var imgImage = e.Item.FindControl("imgImage") as Image;
                imgImage.ImageUrl = GetFullImageUrl(rowView["ImagePath"].ToString().Trim());

                var delBtn = e.Item.FindControl("btnDeleteImage") as ImageButton;
                delBtn.Visible = Editable;
                delBtn.CommandArgument = rowView["ImagePath"].ToString().Trim();
            }
        }

        protected void dlFolders_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView rowView = e.Item.DataItem as DataRowView;

                string folderPath = rowView["FolderPath"].ToString();

                var lbl = e.Item.FindControl("btnFolderName") as LinkButton;
                lbl.Text = rowView["FolderName"].ToString();
                lbl.CommandArgument = folderPath;

                var delBtn = e.Item.FindControl("btnDeleteFolder") as ImageButton;
                delBtn.Visible = CanUserEditFolder();
                delBtn.OnClientClick =
                    string.Format("return confirm('Are you sure you want to delete folder\\n{0}\\nwith all subfolders and files?');", lbl.CommandArgument);
                delBtn.CommandArgument = lbl.CommandArgument;
            }
        }

        protected void dlFiles_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string rowView = e.Item.DataItem as string;

                var hlLink = e.Item.FindControl("hlLink") as HyperLink;
                hlLink.NavigateUrl = Path.Combine(
                    Path.Combine(PropertyVirtualDir, CurrentFoldersPath),
                    HttpUtility.UrlEncode(rowView).Replace("+", "%20"));
                hlLink.Text = rowView;

                var delBtn = e.Item.FindControl("btnDeleteFile") as ImageButton;
                delBtn.Visible = CanUserEditFolder();
                delBtn.OnClientClick =
                    string.Format("return confirm('Are you sure you want to delete file\\n{0}?');", rowView);
                delBtn.CommandArgument = rowView;

                delBtn = e.Item.FindControl("btnMoveFile") as ImageButton;
                delBtn.Visible = CanUserEditFolder();
                delBtn.OnClientClick = "MoveFile('" + rowView + "'); return false;";
            }
        }

        protected void dlImages_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "DeleteImage")
            {
                try
                {
                    string fileName = e.CommandArgument.ToString();
                    File.Delete(Path.Combine(PropertyGalleryPhysicalDir, fileName));

                    RefreshImages();

                }
                catch
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(),
                        "key", string.Format("alert('Error deleting image');"), true);
                }
            }
        }

        protected void dlFiles_ItemCommand(object source, DataListCommandEventArgs e)
        {
            string fileName = e.CommandArgument.ToString();

            if (e.CommandName == "DeleteFile")
            {
                try
                {
                    File.Delete(Path.Combine(Path.Combine(PropertyPhysicalDir, CurrentFoldersPath), fileName));
                    RefreshFilesList(CurrentFoldersPath);
                }
                catch
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(),
                      "key", string.Format("alert('Error deleting file');"), true);
                }
            }            
        }

        void GoToFolder(string path)
        {
            CurrentFoldersPath = path;
            RefreshFoldersList(CurrentFoldersPath);
            RefreshFilesList(CurrentFoldersPath);
            RefreshBreadcrumb(CurrentFoldersPath);
            RefreshImages();
        }

        protected void dlFolders_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "GoToFolder")
            {
                GoToFolder(e.CommandArgument.ToString());
            }
            else if (e.CommandName == "DeleteFolder")
            {
                try
                {
                    Directory.Delete(Path.Combine(PropertyPhysicalDir, e.CommandArgument.ToString()), true);
                    RefreshFoldersList(CurrentFoldersPath);
                }
                catch(Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(),
                      "key", string.Format("alert('Error deleting folder');"), true);
                }                
            }            
        }

        protected void dlBreadcrumb_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string rowView = e.Item.DataItem as string;

                var delBtn = e.Item.FindControl("btnGoToFolder") as ImageButton;
                delBtn.CommandArgument = rowView;

                var lbl = e.Item.FindControl("btnFolderName") as LinkButton;
                string[] split = rowView.Split('\\');
                lbl.Text = split[split.Length - 1];
                lbl.CommandArgument = rowView;
            }
        }

        protected void dlBreadcrumb_ItemCommand(object source, DataListCommandEventArgs e)
        {
            GoToFolder(e.CommandArgument.ToString());
        }

        protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
        {
            switch (eventArgument)
            {
                case "Refresh":
                    GoToFolder(CurrentFoldersPath);
                    break;
                default: base.RaisePostBackEvent(sourceControl, eventArgument); break;
            }
        }

        void DoNormalization(string rootDir)
        {
            var files = new List<string>();
            WalkDirectoryTree(new DirectoryInfo(rootDir), files);

            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);

                foreach (DataRow dr in DocumentFolders.Rows)
                {
                    string prefix1 = dr["Prefix"].ToString().ToUpper() + " ";
                    string prefix2 = dr["Prefix"].ToString().ToUpper() + "_";

                    if (fileName.ToUpper().StartsWith(prefix1) || fileName.ToUpper().StartsWith(prefix2))
                    {
                        string folderName = Path.Combine(rootDir, dr["FolderName"].ToString());
                        string fileFolderName = Path.GetDirectoryName(file);

                        if (!fileFolderName.ToUpper().StartsWith(folderName.ToUpper()))
                        {
                            File.Move(file, Path.Combine(folderName, fileName));
                            break;
                        }
                    }
                }
            }
        }

        void WalkDirectoryTree(DirectoryInfo di, List<string> files)
        {
            foreach (FileInfo fi in di.GetFiles())
            {
                files.Add(fi.FullName);
            }

            foreach (DirectoryInfo din in di.GetDirectories())
            {
                WalkDirectoryTree(din, files);
            }
        }

        protected void lbGallery_Click(object sender, EventArgs e)
        {
            ShowGallery = !ShowGallery;
            divGallery.Visible = ShowGallery;
            if (ShowGallery)
                lbGallery.Text = "Hide gallery";
            else
                lbGallery.Text = "Show gallery";
        }

        protected void RefreshGalleryVisible()
        {
            if (string.IsNullOrEmpty(CurrentFoldersPath))
            {
                lbGallery.Visible = false;
                lbGallery.Text = "Show gallery";
                ShowGallery = false;

                divGallery.Visible = true;
                dlImages.Visible = true;
            }
            else
            {
                lbGallery.Visible = true;
                divGallery.Visible = ShowGallery;
                dlImages.Visible = false;
                if (dlImages.Items.Count == 0)
                    lbGallery.Visible = false;
            }
        }

        protected void btnPrevProperty_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect(btnPrevProperty.PostBackUrl, true);
        }

        protected void btnNextProperty_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect(btnNextProperty.PostBackUrl, true);
        }
    }
}